package com.fast.fast.upms.biz.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fast.fast.common.base.exception.BizException;
import com.fast.fast.upms.api.entity.SysUserRole;
import com.fast.fast.upms.biz.base.util.ClearAuthUtils;
import com.fast.fast.upms.biz.mapper.SysUserRoleMapper;
import com.fast.fast.upms.biz.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lyf
 * @description 针对表【sys_user_role(系统用户角色关联表)】的数据库操作Service实现
 * @createDate 2022/01/01 00:00 周六
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole>
        implements SysUserRoleService {

    @Autowired
    private ClearAuthUtils clearAuthUtils;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addRoles(Long userId, List<?> roleIds) {
        if (ObjectUtil.isEmpty(userId)) {
            throw new BizException("用户id不能为空");
        }

        // 删除系统用户角色关联表数据
        List<Long> ids = list(Wrappers.lambdaQuery(SysUserRole.class)
                .eq(SysUserRole::getUserId, userId)
        ).stream().map(SysUserRole::getId).collect(Collectors.toList());
        removeBatchByIds(ids);

        List<SysUserRole> sysUserRoles = roleIds.stream().map(o -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(Long.valueOf((String) o));
            return sysUserRole;
        }).collect(Collectors.toList());
        saveBatch(sysUserRoles);

        // 清除指定用户的角色编码集合
        clearAuthUtils.clearSpecifiedUserRoleList(Collections.singletonList(userId));
        // 清除指定用户的权限编码集合
        clearAuthUtils.clearSpecifiedUserPermList(Collections.singletonList(userId));
        return true;
    }
}




